package com.hddf.project.auth.service;

import com.hddf.project.auth.dao.AESKeyDao_MongoDB;
import com.hddf.project.auth.dao_impl.AESKeyDaoImpl_MongoDB;
import com.kommii.mongodb_utils.Mongodb_ConnPools;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import org.kommii.common_utils.UUID_Generator;

public class AESKeyService {
	private static AESKeyService aeskey_service = null;
	private static AESKeyDao_MongoDB aeskeyDao_MongoDB = null;
	static {
		if(aeskey_service==null){
			aeskey_service = new AESKeyService();
		}
		if(aeskeyDao_MongoDB==null){
			aeskeyDao_MongoDB = new AESKeyDaoImpl_MongoDB();
		}
	}
	
	public static AESKeyService getInstance(){
		return aeskey_service;
	}
	
	/**
	 * 向 mongodb 数据库添加AES密钥 并返回mongodb中的 _id 
	 */
	public String addAESKey(){
		DBCollection coll  = null;
		try{
			String AESKeyString = UUID_Generator.getUUID().substring(0, 16);
			coll = Mongodb_ConnPools.getMongoDB_Coll("aeskey");
			return aeskeyDao_MongoDB.add(AESKeyString,coll)+" "+AESKeyString;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public boolean deleteAESKey(String id){
		DBCollection coll  = null;
		try{
			coll = Mongodb_ConnPools.getMongoDB_Coll("aeskey");
			return aeskeyDao_MongoDB.delete(id, coll);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean deleteTimeOutAesKeys(long current_time){
		DBCollection coll  = null;
		try{
			coll = Mongodb_ConnPools.getMongoDB_Coll("aeskey");
			return aeskeyDao_MongoDB.deleteTimeOutAesKeys(current_time, coll);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	public DBObject getAESKeyById(String id){
		DBCollection coll  = null;
		try{
			coll = Mongodb_ConnPools.getMongoDB_Coll("aeskey");
			return aeskeyDao_MongoDB.getById(id, coll);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public int getAESKey_validTime(){
		try{
			return AESKeyDaoImpl_MongoDB.getAESKey_validTime();
		}catch(Exception e){
			e.printStackTrace();
			return -1;
		}
	}
	

}
